package cn.tworice.netty.config;

import cn.tworice.netty.hanlder.WebSocketHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Component
public class WebSocketInitializer extends ChannelInitializer<SocketChannel> {

    @Resource
    private WebSocketHandler webSocketHandler;

    @Resource
    private NettyProperties nettyProperties;

    @Override
    protected void initChannel(SocketChannel ch) {
        ch.pipeline()
                .addLast(new HttpServerCodec()) // 编解码器
                .addLast(new ChunkedWriteHandler())
                .addLast(new HttpObjectAggregator(this.nettyProperties.getMaxContentLength()))
                .addLast(new WebSocketServerProtocolHandler(this.nettyProperties.getPath()))
                .addLast(this.webSocketHandler); // 添加 WebSocket 处理器

//        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/websocket", null, true, 65536, true) {
//            @Override
//            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                if (msg instanceof FullHttpRequest) {
//
//                    FullHttpRequest req = (FullHttpRequest) msg;
//                    HttpHeaders headers = req.headers();
//                    System.out.println(headers.get("Authorization"));
//
////                    QueryStringDecoder decoder = new QueryStringDecoder(req.uri(),StandardCharsets.UTF_8);
////                    System.out.println("Authorization: " + decoder.parameters().get("authorization").get(0));
//                    // TODO: handle w and t parameters
//                } else {
//                    super.channelRead(ctx, msg);
//                }
//            }
//        });
    }
}
